# _*_ coding: utf-8 _*_
__author__ = 'yinlei'
__date__ = '2018-05-18 8:23'

from wtforms import StringField, PasswordField, IntegerField, ValidationError
from wtforms.validators import Email, Length, InputRequired, EqualTo

from apps.bases.forms import BaseForm
from utils import zlcache
from flask import g
from .models import CMSUser


class LoginForm(BaseForm):
    email = StringField(validators=[Email(message='请输入正确的邮箱格式'), InputRequired(message='请输入邮箱')])
    password = PasswordField(validators=[Length(6, 20, message='请输入正确密码')])
    remember = IntegerField()


class ResetpwdForm(BaseForm):
    oldpwd = PasswordField(validators=[Length(6, 20, message='请正确输入旧密码')])
    newpwd = PasswordField(validators=[Length(6, 20, message='请正确输入新密码')])
    newpwd2 = PasswordField(validators=[Length(6, 20, message='请正确输入新密码'), EqualTo('newpwd', message='密码不一致')])


class ResetEmailform(BaseForm):
    email = StringField(validators=[Email(message='请输入正确的邮箱格式')])
    captcha = StringField(validators=[Length(8, 8, message='请输入正确长度的验证码')])

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        code = zlcache.get(email)
        if not code or captcha.lower() != code.lower():
            raise ValidationError(message='请输入正确的验证码')

    def validate_email(self, field):
        email= field.data
        user = g.cms_user
        if user.email == email:
            raise ValidationError('不能修改为相同邮箱')
        user_q = CMSUser.query.filter_by(email=email).first()
        if user_q:
            raise ValidationError('此邮箱已经注册')

class AddBannersForm(BaseForm):
    name = StringField(validators=[InputRequired(message='请输入轮播图名称')])
    image_url = StringField(validators=[InputRequired(message='请输入轮播图片链接')])
    link_url = StringField(validators=[InputRequired(message='请输入轮播图跳转链接')])
    priority = IntegerField(validators=[InputRequired(message='请输入优先级')])

class updateBannersForm(AddBannersForm):
    banner_id = IntegerField(validators=[InputRequired(message='请输入轮播图id')])

class AddBoardForm(BaseForm):
    name = StringField(validators=[InputRequired(message='请输入板块名称!')])

class UpdateBoardForm(BaseForm):
    id = IntegerField(InputRequired(message='请输入板块id'))
    name = StringField(InputRequired(message='请输入板块名称'))


class DeleteBoardForm(BaseForm):
    id = IntegerField(InputRequired(message='请输入板块id'))